package com.antdesignbackend.backend.util;

import org.apache.commons.codec.binary.Base64;
import net.sf.json.JSONObject;

import java.util.Map;

public class WXCore {

    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";

    /**
     * 解密数据
     * @return
     * @throws Exception
     */
    public static String decrypt(String appId, String encryptedData, String sessionKey, String iv){
        String result = "";
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if(null != resultByte && resultByte.length > 0){
                result = new String(WxPKCS7Encoder.decode(resultByte));
                JSONObject jsonObject = JSONObject.fromObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
                if(!appId.equals(decryptAppid)){
                    result = "";
                }
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws Exception{
        String appId = "wx740d16af3bd07004";
        String encryptedData = "pT/Pb7dNZRUDBztC5IXfh2Je/1JCjMRHYNgE8nw7NItE8ixFXhcTafEDwqYEsT4UmVKUHB16sQ/2cX1GqCvpI+LZdQI/mC8/9tvmhAMSR0ofXLJ5vVkYidpv1kROta+jjyIf4LBFPntdf2BOq3pHWfhIXGuHfIujjOrWizTSrwtfVzPNWLYxF04NIBk8DTxneAPfBQTpY2CDy3yZ5ppRXQ==";
        String sessionKey = "QfOu5P8uqnJaG7mrQ2NQ2Q==";
        String iv = "2UaNwfPNtxOYMBO7zb1hlw==";
        String phoneStr=decrypt(appId, encryptedData, sessionKey, iv);
        System.out.println("phoneStr:"+phoneStr);
        JSONObject pa=JSONObject.fromObject(phoneStr);
        String phone=pa.getString("phoneNumber");
        System.out.println(phone);
    }

}
